import 'package:flutter/material.dart';
import './client_dio.dart';
import 'dart:convert';
import 'dart:core';
import './routes/align.dart';
import "myitem_edit.dart";
import "myitems_new.dart";
import 'package:file_picker/file_picker.dart';
class ItemsHome extends StatefulWidget {
  @override
  State createState() => new ItemsHomeState();
}
class ItemsHomeState extends State<ItemsHome> {
  var start=0;
  var limit=10;
  var total=0;
  var res;
  var query="";
  var rows=[TableRow(
              decoration: BoxDecoration(color: Colors.grey[200]),
              children: 
                [
                  Text("id"),
                  Text("bh"),
                  Text("name"),
                  Text("规格"),
                  Text("单位"),
                  Text("op"),
                ]
              )];
  final TextEditingController t1 = new TextEditingController(text: "0");
  final TextEditingController t2 = new TextEditingController(text: "0");
  final TextEditingController at_Controller = new TextEditingController(text:"1");
  TextEditingController search_Controller = new TextEditingController();
  //TextEditingController name_Controller = new TextEditingController();
  void  login_click() async{
    FilePickerResult? result = await FilePicker.platform.pickFiles();
    if (result != null) {
      print(result.files.single.path);// File file = File(result.files.single.path);
    } else {
      print("null");
      // User canceled the picker
    }
  }
  void load_data(){
      items({"limit":limit,'start':start,'query':query}, (r) {
        res=json.decode(r);
        print(res);
        total=res["total"];
        var newRows=<TableRow>[];
        newRows.add(TableRow(
              decoration: BoxDecoration(color: Colors.grey[200]),
              children: 
                [
                  Text("id"),
                  Text("bh"),
                  Text("name"),
                  Text("op"),
                ]
              ));
        for(var i=0;i<res["data"].length;i++){
      newRows.add(TableRow(
          children: ([
            Text(res["data"][i]["id"].toString()),
            Text(res["data"][i]["bh"]==null?"":res["data"][i]["bh"]),
            Text(res["data"][i]["name"]==null?"":res["data"][i]["name"]),
            Text(res["data"][i]["guige"]==null?"":res["data"][i]["guige"]),
            Text(res["data"][i]["danwei"]==null?"":res["data"][i]["danwei"]),
            Row(
              children: [new MaterialButton(
              child: new Text("edit"),
              color: Colors.greenAccent,
              onPressed: (){doEdit2(i);},
            ),
            new MaterialButton(
              child: new Text("delete"),
              color: Colors.greenAccent,
              onPressed: (){doDelete(i);},
            )
            ])
          ]),
        ));
    }
        setState((){
          rows=newRows;
        });
      }, err_treat);
  }
  void doPrev(){
    if(res==null) return;
    start-=limit;
    if(start<0) start=0;
    load_data();
  }
  void doGo(){
    if(res==null) return;
    start=int.parse(at_Controller.text);
    if(start<0) start=0;
    load_data(); 
  }
  void do_search(){
    start=0;
    query=search_Controller.text;
    load_data();
  }
  void doNext(){
    if(res==null) return;
    start+=limit;
    if(start>res["total"]-limit) start=res["total"]-limit;
    if(start<0) start=0;
    load_data();
  }
  void do_new(){
    post("/rest/Item/", {"name":"new","bh":"001"},(r){
      print(r);
    }, (e){
      print(e);
    });
    
  }
  void puti(id,name){
    put("/rest/Item/", {"id":id,"name":name},(r){
      print(r);
    }, (e){
      print(e);
    });
  }
  void deletei(id){
    delete1("/rest/Item/", {"id":id},(r){
      print(r);
    }, (e){
      print(e);
    });
  }
  void doDelete(i) async{
    showDialog(context: context, builder: (BuildContext context){
      return     Dialog(
      child: Container(
        height: 300,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            FlutterLogo(size: 150,),
            Text(res["data"][i]["name"],style:TextStyle(fontSize: 20),),
            ElevatedButton(
            onPressed: (){
              deletei(res["data"][i]["id"]);
              Navigator.of(context).pop();
            }, child: Text("Ok")),
            ElevatedButton(
            onPressed: (){
              Navigator.of(context).pop();

            }, child: Text("Cancel"))
          ],
        ),
      ),
      );
    });
  }
  void doEdit2(i){
    //Navigator.push(
    //  context,
    //  MaterialPageRoute(
    //    builder: (context) {
    //      return ItemEditRoute();
    //    },
    //  ),
    //);
    Navigator.pushNamed(
      context,
      ItemArgumentsScreen.routeName,
      arguments: ItemArguments(
        res["data"][i]["id"],
        res["data"][i]["name"],
        guige: res["data"][i]["guige"] ?? "",
        danwei: res["data"][i]["danwei"] ?? "",
      ),
    );
  }
  //void doEdit(i) async{

  //  showDialog(context: context, builder: (BuildContext context){
  //    return     Dialog(
  //    child: Container(
  //      height: 300,
  //      child: Column(
  //        mainAxisAlignment: MainAxisAlignment.spaceBetween,
  //        children: [
  //          FlutterLogo(size: 150,),
  //          Text(res["data"][i]["name"],style:TextStyle(fontSize: 20),),
  //          TextField(controller:  name_Controller,
  //            decoration: InputDecoration(labelText: "name"),
  //            ),
  //          ElevatedButton(
  //          onPressed: (){
  //            puti(res["data"][i]["id"],res["data"][i]["name"]);
  //            Navigator.of(context).pop();
  //            //delete 
  //          }, child: Text("Ok")),
  //          ElevatedButton(
  //          onPressed: (){
  //            Navigator.of(context).pop();

  //          }, child: Text("Cancel"))
  //        ],
  //      ),
  //    ),
  //    );
  //  });  
  //}
  void enterRoute(){
    var result = Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) {
                return AlignRoute();
              },
            ),
          );
          print("路由返回值: $result");
  }

  void doClear() {

    setState(() {
      rows=[TableRow(
              decoration: BoxDecoration(color: Colors.grey[200]),
              children: 
                [
                  Text("用户"),
                  Text("仪器型号"),
                  Text("仪器编号"),
                ]
              )];
    });
  }
  _addPadding(List<Widget> w) {
    return w
        .map((e) => Padding(
              padding: EdgeInsets.all(6),
              child: e,
            ))
        .toList();
  }
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Container(
        padding: const EdgeInsets.all(40.0),
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
        //Row(
        //  mainAxisAlignment: MainAxisAlignment.center,
        //      children: <Widget>[
        //  //ElevatedButton(
        //  //  onPressed: (){
        //  //    Navigator.of(context).pop();

        //  //  }, child: Text("Back")),
        //  ElevatedButton(
        //  child: Text("Align"),
        //  onPressed: (){
        //    Navigator.push(
        //      context,
        //      MaterialPageRoute(
        //        builder: (context) {
        //          return AlignRoute();
        //        },
        //      ),
        //    );
        //  }
        //  )]
        //),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[

          ElevatedButton(
          child: Text("login"),
          onPressed: login_click
          ),
          Expanded(
            child:TextField(controller:  search_Controller,
              decoration: InputDecoration(labelText: "name"),
              ),
          ),
          ElevatedButton(
          child: Text("search"),
          onPressed: do_search
          ),
          ElevatedButton(
          child: Text("new"),
          onPressed: do_new
          ),
          ]
        ),
        Table(
          border: TableBorder.all(),
          defaultVerticalAlignment: TableCellVerticalAlignment.middle,
          children: rows,
        ),
            new Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Expanded(
                  child:TextField(controller:  at_Controller,
                    decoration: InputDecoration(labelText: "name"),
                    ),
                ),
                new MaterialButton(
                  child: new Text("go"),
                  color: Colors.greenAccent,
                  onPressed: doGo,
                ),
                new MaterialButton(
                  child: new Text("prev"),
                  color: Colors.greenAccent,
                  onPressed: doPrev,
                ),
                new Text(start.toString()+"/"+total.toString()
                ),
                new MaterialButton(
                  child: new Text("next"),
                  color: Colors.greenAccent,
                  onPressed: doNext,
                ),
              ],
            )
          ],
        ),
      ),
    );
  }
}

